#!/usr/bin/env python
# Copyright (C) 2007 by Xyhthyx <xyhthyx@gmail.com>

# This file is part of Parcelle.

# Parcelle is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

# Parcelle is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys

# Hidden option used by the startup
# file. If parcelle.start exists it
# will launch Parcelle at startup
if '--startup' in sys.argv:
	startup = os.path.join(os.path.join(os.environ['HOME'], '.parcelle'), 'parcelle.start')
	if not os.path.exists(startup):
		# Launch on startup is turned off
		sys.exit(0)

import atexit
from subprocess import Popen

# Check for running instances
# FIXME: Need a better way of checking
#        running pid instances
try:
	# Check if pid file exists, if so open it
	pidfile_name = '/tmp/parcelle.' + os.environ['LOGNAME']
	pidfile = file(pidfile_name)
	pid = pidfile.read()
	pidfile.close()
	# Check if pid in file is running
	try:
		# Send kill signal 0 to check pid
		os.kill(int(pid), 0)
		ps = True
	except OSError:
		# Checked pid is not running
		ps = False
	if not ps:
		# Checked pid not running, removing old file
		# and launching...
		os.remove(pidfile_name)
		p = os.getpid()
		pidfile = file(pidfile_name, 'w')
		pidfile.write('%s' % p)
		pidfile.close()
		atexit.register(lambda:os.remove(pidfile_name))
		import parcelle.start
	else:
		# The checked pid is running, exiting..
		print 'An instance of Parcelle is already running.'
		sys.exit(1)
except IOError:
	# Open pid file failed, launching..
	pidfile_name = '/tmp/parcelle.' + os.environ['LOGNAME']
	pid = os.getpid()
	pidfile = file(pidfile_name, 'w')
	pidfile.write('%s' % pid)
	pidfile.close()
	atexit.register(lambda:os.remove(pidfile_name))
	import parcelle.start
